package com.cyy.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.model.dto.paymentbill.PaymentBillAddRequest;
import com.cyy.springbootinit.model.dto.paymentbill.PaymentBillEditRequest;
import com.cyy.springbootinit.model.dto.paymentbill.PaymentBillQueryRequest;
import com.cyy.springbootinit.model.dto.paymentbill.PaymentBillUpdateRequest;
import com.cyy.springbootinit.model.entity.PaymentBill;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.PaymentBillVO;
import com.cyy.springbootinit.service.PaymentBillService;
import com.cyy.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 缴费单表接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/paymentBill")
@Slf4j
public class PaymentBillController {

    @Resource
    private PaymentBillService paymentBillService;

    @Resource
    private UserService userService;

    // region 增删改查
    /**
     * 创建缴费单表
     *
     * @param paymentBillAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPaymentBill(@RequestBody PaymentBillAddRequest paymentBillAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(paymentBillAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        PaymentBill paymentBill = new PaymentBill();
        BeanUtils.copyProperties(paymentBillAddRequest, paymentBill);
        // 数据校验
        paymentBillService.validPaymentBill(paymentBill, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        paymentBill.setUserId(loginUser.getId());
        paymentBill.setPaymentDate(new Date());
        // 写入数据库
        boolean result = paymentBillService.save(paymentBill);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newPaymentBillId = paymentBill.getPaymentId();
        return ResultUtils.success(newPaymentBillId);
    }

    /**
     * 删除缴费单表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePaymentBill(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        PaymentBill oldPaymentBill = paymentBillService.getById(id);
        ThrowUtils.throwIf(oldPaymentBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPaymentBill.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = paymentBillService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新缴费单表（仅管理员可用）
     *
     * @param paymentBillUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePaymentBill(@RequestBody PaymentBillUpdateRequest paymentBillUpdateRequest) {
        if (paymentBillUpdateRequest == null || paymentBillUpdateRequest.getPaymentId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        PaymentBill paymentBill = new PaymentBill();
        BeanUtils.copyProperties(paymentBillUpdateRequest, paymentBill);
        // 数据校验
        paymentBillService.validPaymentBill(paymentBill, false);
        // 判断是否存在
        long id = paymentBillUpdateRequest.getPaymentId();
        PaymentBill oldPaymentBill = paymentBillService.getById(id);
        ThrowUtils.throwIf(oldPaymentBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = paymentBillService.updateById(paymentBill);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取缴费单表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PaymentBillVO> getPaymentBillVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        PaymentBill paymentBill = paymentBillService.getById(id);
        ThrowUtils.throwIf(paymentBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(paymentBillService.getPaymentBillVO(paymentBill, request));
    }

    /**
     * 分页获取缴费单表列表（仅管理员可用）
     *
     * @param paymentBillQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<PaymentBill>> listPaymentBillByPage(@RequestBody PaymentBillQueryRequest paymentBillQueryRequest) {
        long current = paymentBillQueryRequest.getCurrent();
        long size = paymentBillQueryRequest.getPageSize();
        // 查询数据库
        Page<PaymentBill> paymentBillPage = paymentBillService.page(new Page<>(current, size),
                paymentBillService.getQueryWrapper(paymentBillQueryRequest));
        return ResultUtils.success(paymentBillPage);
    }

    /**
     * 分页获取缴费单表列表（封装类）
     *
     * @param paymentBillQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PaymentBillVO>> listPaymentBillVOByPage(@RequestBody PaymentBillQueryRequest paymentBillQueryRequest,
                                                               HttpServletRequest request) {
        long current = paymentBillQueryRequest.getCurrent();
        long size = paymentBillQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<PaymentBill> paymentBillPage = paymentBillService.page(new Page<>(current, size),
                paymentBillService.getQueryWrapper(paymentBillQueryRequest));
        // 获取封装类
        return ResultUtils.success(paymentBillService.getPaymentBillVOPage(paymentBillPage, request));
    }

    /**
     * 分页获取当前登录用户创建的缴费单表列表
     *
     * @param paymentBillQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PaymentBillVO>> listMyPaymentBillVOByPage(@RequestBody PaymentBillQueryRequest paymentBillQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(paymentBillQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        paymentBillQueryRequest.setUserId(loginUser.getId());
        long current = paymentBillQueryRequest.getCurrent();
        long size = paymentBillQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<PaymentBill> paymentBillPage = paymentBillService.page(new Page<>(current, size),
                paymentBillService.getQueryWrapper(paymentBillQueryRequest));
        // 获取封装类
        return ResultUtils.success(paymentBillService.getPaymentBillVOPage(paymentBillPage, request));
    }

    /**
     * 编辑缴费单表（给用户使用）
     *
     * @param paymentBillEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPaymentBill(@RequestBody PaymentBillEditRequest paymentBillEditRequest, HttpServletRequest request) {
        if (paymentBillEditRequest == null || paymentBillEditRequest.getPaymentId()<= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        PaymentBill paymentBill = new PaymentBill();
        BeanUtils.copyProperties(paymentBillEditRequest, paymentBill);
        // 数据校验
        paymentBillService.validPaymentBill(paymentBill, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = paymentBillEditRequest.getPaymentId();
        PaymentBill oldPaymentBill = paymentBillService.getById(id);
        ThrowUtils.throwIf(oldPaymentBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPaymentBill.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = paymentBillService.updateById(paymentBill);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
